package job

import (
	"fmt"
	"gorm.io/gorm"
	"synch-data/db/conf"
	"synch-data/db/service"
	"synch-data/models"
)




func SynchData(leaderConf conf.LeaderConfig)  {



	datas := service.QueryDataMaster(leaderConf)

	dbSlaver := leaderConf.GetSlaveCon()
	dbMaster := leaderConf.GetMasterCon()

	if datas == nil{
		return
	}

	ret := doItemJob(dbSlaver,dbMaster,datas)

	if !ret {
		return
	}
	fmt.Println("finish one item...")

}

func doItemJob(dbSlaver *gorm.DB,dbMaster *gorm.DB,dbData []models.SynchData)bool  {
	txSlaver := dbSlaver.Begin()
	defer rollbackSlave(txSlaver)

	errSlave := handleSlaver(dbData,txSlaver).Error
	if errSlave != nil{
		txSlaver.Rollback()
		fmt.Println(errSlave)
		return false
	}


	errMaster := handleMaster(dbData,dbMaster).Error

	if errMaster != nil{
		txSlaver.Rollback()
		fmt.Println(errMaster)
		return false
	}

	txSlaver.Commit()

	return true
}


func rollbackSlave(tx *gorm.DB)  {
	err := recover()
	if err != nil {
		fmt.Println("catch exception")
		fmt.Println(err)
		tx.Rollback()
	}
}

func handleSlaver(dbData []models.SynchData,db *gorm.DB) *gorm.DB {
	db = insertSlaver(dbData,db)
	return db
}

func handleMaster(dbData []models.SynchData,db *gorm.DB) *gorm.DB  {
	return deleteMaster(dbData,db)
}




func deleteMaster(row []models.SynchData,db *gorm.DB) *gorm.DB  {
	return service.DeleteMaster(row,db)
}

func insertSlaver(rows []models.SynchData,db *gorm.DB)*gorm.DB  {
	return service.InsertSlaver(rows,db)
}

